import { Project, useProjectStore } from '@/store/project-store';
import { IPage } from './types';
import { guid, traverseTree } from '@/util';
import { System } from '@/store/system-repository';
import { RouteRecordNameGeneric } from 'vue-router';
import { PROJECT_DETAIL_ROUTE } from '@/router';

export function useProjectService() {
  const projectStore = useProjectStore();

  const projectDetailPages = computed(() => {
    const projectDetailPages_ = new Set();
    traverseTree(
      node => {
        projectDetailPages_.add(node.name);
      },
      [PROJECT_DETAIL_ROUTE],
    );
    return projectDetailPages_;
  });

  // 获取当前用户参与的项目
  const projects = (): Promise<IPage<Project>> => {
    return new Promise(resolve => {
      resolve({ current: 1, size: 10, records: projectStore.projects });
    });
  };

  const addOrEditProject = (project: Project): Promise<Project> => {
    let project_ = project;
    if (project.id) {
      // TODO 编辑
    } else {
      project_ = { ...project, id: guid() };
      projectStore.addProject(project_);
    }
    return new Promise(resolve => {
      resolve(project_);
    });
  };

  // 获取项目建设的系统
  const systems = (projectId: string): Promise<IPage<System>> => {
    return projectStore.systems(projectId);
  };

  const getIsProjectDetail = (routeName: RouteRecordNameGeneric): boolean => {
    return projectDetailPages.value.has(routeName as string);
  };

  return { projects, addOrEditProject, systems, getIsProjectDetail };
}
